package cn.itcast.hotel.listen;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.constant.MqConstant;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author Vsunks.v
 * @Date 2022/8/9 11:53
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description:
 */
@Component
public class HotelListener {
    @Autowired
    private IHotelService hotelService;
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(MqConstant.HOTEL_INSERT_QUEUE),
                    exchange = @Exchange(value = MqConstant.HOTEL_EXCHANGE,type = ExchangeTypes.DIRECT),
                    key = MqConstant.HOTEL_INSERT_KEY
            )
    })
    public void listenHotelInsert(String id) throws Exception {
        Hotel hotel = hotelService.getById(Long.valueOf(id));
        HotelDoc hotelDoc = new HotelDoc(hotel);
        IndexRequest request = new IndexRequest(EsConstant.index);
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);

        client.index(request, RequestOptions.DEFAULT);
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(MqConstant.HOTEL_DELETE_QUEUE),
                    exchange = @Exchange(value = MqConstant.HOTEL_EXCHANGE,type = ExchangeTypes.DIRECT),
                    key = MqConstant.HOTEL_DELETE_KEY
            )
    })
    public void listenHotelDelete(String id) throws Exception {
        DeleteRequest deleteRequest = new DeleteRequest(EsConstant.index,id);
        client.delete(deleteRequest,RequestOptions.DEFAULT);
    }
}
